package com.rpframework.core.config.zookeeper;

import org.apache.commons.lang.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * 
 * @author 刘兴
 */
public class ZooKeeperFactory {
	/**
	 * 连接字符
	 */
	public static String connectString;

	public static String getConnectString() {
		return connectString;
	}

	public static void setConnectString(String connectString) {
		ZooKeeperFactory.connectString = connectString;
	}

	public static int getMaxRetries() {
		return maxRetries;
	}

	public static void setMaxRetries(int maxRetries) {
		ZooKeeperFactory.maxRetries = maxRetries;
	}

	public static int getBaseSleepTimems() {
		return baseSleepTimems;
	}

	public static void setBaseSleepTimems(int baseSleepTimems) {
		ZooKeeperFactory.baseSleepTimems = baseSleepTimems;
	}

	public static String getNameSpace() {
		return nameSpace;
	}

	public static void setNameSpace(String nameSpace) {
		ZooKeeperFactory.nameSpace = nameSpace;
	}

	/**
	 * 最大连接数
	 */
	public static int maxRetries = 300;
	/**
	 * 连接超时
	 */
	public static int baseSleepTimems = 30000;
	/**
	 * 命名空间
	 */
	public static String nameSpace = "cfg";

	/**
	 * 连接zookeeper
	 * 
	 * @return 客户端
	 */
	public CuratorFramework get() {
		if (StringUtils.isBlank(connectString)) {
			throw new NullPointerException("连接地址不能为空");
		}
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimems, maxRetries);
		CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectString)
				.retryPolicy(retryPolicy).namespace(nameSpace).build();
		client.start();
		return client;
	}
}